package com.np.service_demo1;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

import com.np.service_demo1.services.BindService;
import com.np.service_demo1.services.StartService;

/**
 * 这个例子主要实现两种方式启动和停止服务：
 * Start 方式启动和停止服务
 * Bind 方式启动和停止服务
 */
public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private Button btnStart, btnBind;
    private BindService mService = null;
    private boolean mBind = false;
    private ServiceConnection mConn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(TAG, "onServiceConnected.");
            mBind = true;
            BindService.XBinder binder = (BindService.XBinder) service;
            mService = binder.getServices();
            Log.i(TAG, "getRandomNumber --> " + mService.getRandomNumber());
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(TAG, "onServiceDisconnected.");
            mBind = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnStart = findViewById(R.id.btn_start);
        btnBind = findViewById(R.id.btn_bind);

        // Start 方式启动和停止服务
        btnStart.setOnClickListener(v -> {
            if (btnStart.getText().equals("Start")) {
                Intent intent = new Intent(this, StartService.class);
                startService(intent);
                btnStart.setText("Stop");
            } else {
                Intent intent = new Intent(this, StartService.class);
                stopService(intent);
                btnStart.setText("Start");
            }
        });

        // Bind 方式启动和停止服务
        btnBind.setOnClickListener(v -> {
            if (btnBind.getText().equals("Bind")) {
                Intent intent = new Intent(this, BindService.class);
                intent.putExtra("from", TAG);
                bindService(intent, mConn, BIND_AUTO_CREATE);
                btnBind.setText("Unbind");
            } else {
                if (mBind) {
                    unbindService(mConn);
                }
                btnBind.setText("Bind");
            }
        });
    }
}